<template>
  <div class="article-carousel">
    <el-carousel
      v-if="articles.length > 0"
      :height="height"
      :interval="interval"
      :arrow="arrow"
      :indicator-position="indicatorPosition"
      :autoplay="autoplay"
      :loop="loop"
      :pause-on-hover="pauseOnHover"
      @change="handleSlideChange"
    >
      <el-carousel-item
        v-for="(article, index) in articles"
        :key="article.id || index"
        class="carousel-item"
      >
        <div class="article-slide" @click="handleArticleClick(article)">
          <!-- 文章图片 -->
          <div class="article-image">
            <img
              :src="getArticleImage(article)"
              :alt="article.title"
              @error="handleImageError"
            />
            <div class="image-overlay">
              <div class="article-info">
                <h3 class="article-title">{{ article.title }}</h3>
                <p v-if="showSummary && article.summary" class="article-summary">
                  {{ article.summary }}
                </p>
                <div class="article-meta">
                  <span v-if="showDate" class="publish-date">
                    {{ formatDate(article.publishTime || article.createdAt) }}
                  </span>
                  <span v-if="showCategory && article.categoryName" class="category">
                    {{ article.categoryName }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-carousel-item>
    </el-carousel>
    
    <!-- 无数据状态 -->
    <div v-else class="no-data">
      <el-empty description="暂无文章数据" />
    </div>
    
    <!-- 文章详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      :title="currentArticle?.title"
      width="800px"
      @close="handleDetailClose"
    >
      <div v-if="currentArticle" class="article-detail">
        <div class="detail-image" v-if="getArticleImage(currentArticle)">
          <img :src="getArticleImage(currentArticle)" :alt="currentArticle.title" />
        </div>
        <div class="detail-content">
          <h2>{{ currentArticle.title }}</h2>
          <div class="detail-meta">
            <span>发布时间：{{ formatDate(currentArticle.publishTime || currentArticle.createdAt) }}</span>
            <span v-if="currentArticle.categoryName">分类：{{ currentArticle.categoryName }}</span>
            <span v-if="currentArticle.author">作者：{{ currentArticle.author }}</span>
          </div>
          <div class="detail-summary" v-if="currentArticle.summary">
            <p>{{ currentArticle.summary }}</p>
          </div>
          <div class="detail-body" v-if="currentArticle.content" v-html="currentArticle.content"></div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

interface Article {
  id: number | string
  title: string
  summary?: string
  content?: string
  image?: string
  author?: string
  publishTime?: string
  createdAt?: string
  categoryName?: string
  [key: string]: any
}

interface Props {
  // 文章数据
  articles?: Article[]
  
  // 轮播配置
  height?: string
  interval?: number
  arrow?: 'always' | 'hover' | 'never'
  indicatorPosition?: 'outside' | 'none' | ''
  autoplay?: boolean
  loop?: boolean
  pauseOnHover?: boolean
  
  // 显示配置
  showSummary?: boolean
  showDate?: boolean
  showCategory?: boolean
  showDetail?: boolean
  
  // 默认图片
  defaultImage?: string
  
  // 点击行为
  clickable?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  articles: () => [],
  height: '400px',
  interval: 5000,
  arrow: 'hover',
  indicatorPosition: 'outside',
  autoplay: true,
  loop: true,
  pauseOnHover: true,
  showSummary: true,
  showDate: true,
  showCategory: true,
  showDetail: true,
  defaultImage: '/images/default-article.jpg',
  clickable: true
})

const emit = defineEmits<{
  'article-click': [article: Article]
  'slide-change': [index: number, article: Article]
}>()

// 响应式数据
const detailVisible = ref(false)
const currentArticle = ref<Article | null>(null)
const currentSlideIndex = ref(0)

// 计算属性
const validArticles = computed(() => {
  return props.articles.filter(article => article && article.title)
})

// 方法
const getArticleImage = (article: Article): string => {
  if (article.image) {
    // 如果是相对路径，添加域名前缀
    if (article.image.startsWith('/')) {
      return `${window.location.origin}${article.image}`
    }
    return article.image
  }
  return props.defaultImage
}

const formatDate = (dateStr?: string): string => {
  if (!dateStr) return ''
  
  try {
    const date = new Date(dateStr)
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    })
  } catch (error) {
    return dateStr
  }
}

const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  if (img.src !== props.defaultImage) {
    img.src = props.defaultImage
  }
}

const handleSlideChange = (index: number) => {
  currentSlideIndex.value = index
  const article = validArticles.value[index]
  if (article) {
    emit('slide-change', index, article)
  }
}

const handleArticleClick = (article: Article) => {
  if (!props.clickable) return
  
  emit('article-click', article)
  
  if (props.showDetail) {
    currentArticle.value = article
    detailVisible.value = true
  }
}

const handleDetailClose = () => {
  currentArticle.value = null
}

// 监听文章数据变化
watch(() => props.articles, (newArticles) => {
  if (newArticles.length === 0) {
    currentSlideIndex.value = 0
  }
}, { immediate: true })

// 暴露方法
defineExpose({
  goToSlide: (index: number) => {
    if (index >= 0 && index < validArticles.value.length) {
      currentSlideIndex.value = index
    }
  },
  getCurrentArticle: () => validArticles.value[currentSlideIndex.value],
  getCurrentIndex: () => currentSlideIndex.value
})
</script>

<style scoped lang="scss">
.article-carousel {
  width: 100%;
  
  .carousel-item {
    width: 100%;
    height: 100%;
  }
  
  .article-slide {
    width: 100%;
    height: 100%;
    position: relative;
    cursor: pointer;
    overflow: hidden;
    
    &:hover .image-overlay {
      opacity: 1;
    }
  }
  
  .article-image {
    width: 100%;
    height: 100%;
    position: relative;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      transition: transform 0.3s ease;
    }
    
    &:hover img {
      transform: scale(1.05);
    }
  }
  
  .image-overlay {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background: linear-gradient(transparent, rgba(0, 0, 0, 0.8));
    color: white;
    padding: 30px 20px 20px;
    opacity: 0.9;
    transition: opacity 0.3s ease;
  }
  
  .article-info {
    .article-title {
      font-size: 18px;
      font-weight: 600;
      margin: 0 0 8px 0;
      line-height: 1.4;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
    
    .article-summary {
      font-size: 14px;
      line-height: 1.5;
      margin: 0 0 12px 0;
      opacity: 0.9;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
    
    .article-meta {
      display: flex;
      gap: 16px;
      font-size: 12px;
      opacity: 0.8;
      
      span {
        display: flex;
        align-items: center;
        
        &.category {
          background: rgba(255, 255, 255, 0.2);
          padding: 2px 8px;
          border-radius: 12px;
        }
      }
    }
  }
  
  .no-data {
    height: 400px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f5f7fa;
    border-radius: 8px;
  }
  
  // 文章详情对话框样式
  .article-detail {
    .detail-image {
      margin-bottom: 20px;
      
      img {
        width: 100%;
        max-height: 300px;
        object-fit: cover;
        border-radius: 8px;
      }
    }
    
    .detail-content {
      h2 {
        font-size: 24px;
        font-weight: 600;
        margin: 0 0 16px 0;
        color: #303133;
      }
      
      .detail-meta {
        display: flex;
        gap: 20px;
        margin-bottom: 20px;
        padding-bottom: 16px;
        border-bottom: 1px solid #ebeef5;
        font-size: 14px;
        color: #909399;
      }
      
      .detail-summary {
        margin-bottom: 20px;
        padding: 16px;
        background: #f8f9fa;
        border-radius: 8px;
        
        p {
          margin: 0;
          line-height: 1.6;
          color: #606266;
        }
      }
      
      .detail-body {
        line-height: 1.8;
        color: #303133;
        
        :deep(img) {
          max-width: 100%;
          height: auto;
          border-radius: 4px;
          margin: 8px 0;
        }
        
        :deep(p) {
          margin: 12px 0;
        }
      }
    }
  }
}

// 轮播图指示器样式优化
:deep(.el-carousel__indicators) {
  .el-carousel__indicator {
    .el-carousel__button {
      background-color: rgba(255, 255, 255, 0.5);
      border: 2px solid rgba(255, 255, 255, 0.8);
    }
    
    &.is-active .el-carousel__button {
      background-color: #409eff;
      border-color: #409eff;
    }
  }
}

// 轮播图箭头样式优化
:deep(.el-carousel__arrow) {
  background-color: rgba(0, 0, 0, 0.5);
  border: none;
  color: white;
  
  &:hover {
    background-color: rgba(0, 0, 0, 0.7);
  }
}
</style>
